//
//  FRPPhotoImporter.m
//  FunctionalReactivePixels
//
//  Created by Linyongzhi on 2017/4/5.
//
//

#import "FRPPhotoImporter.h"
#import "FRPPhotoModel.h"

#import "SCMockDataHelper.h"

@implementation FRPPhotoImporter

+ (RACReplaySubject*)importPhotos {
    RACReplaySubject *subject = [RACReplaySubject subject];
    
    NSDictionary *photoDataDic = [SCMockDataHelper loadJSONDataFromFile:@"PhotosModel"];
    
    if (photoDataDic) {
        [subject sendNext:[[[photoDataDic[@"photos"] rac_sequence] map: ^id(RACTuple *photoDictionary) {
            NSDictionary *photoDic = [photoDictionary objectAtIndex:1];
            
            FRPPhotoModel *model = [FRPPhotoModel new];
            [self configurePhotoModel:model
                       withDictionary:photoDic];
            [self downloadThumbnailForPhotoModel:model];
            return model;
        }] array]];
        [subject sendCompleted];
    }else {
        // 随便发个错误先
        [subject sendError:[NSError errorWithDomain:NSURLErrorDomain code:199 userInfo:nil]];
    }
    return subject;
}

+ (NSString*)urlForImageSize:(NSInteger)size inArray:(NSArray*)array {
    return [[[[[array rac_sequence] filter:^BOOL(NSDictionary *value) {
        return [value[@"size"] integerValue] == size;
    }] map:^id(id value) {
        return value[@"url"];
    }] array] firstObject];
}

+ (void)configurePhotoModel:(FRPPhotoModel*)photoModel withDictionary:(NSDictionary*)dictionary{
    // Basics details fetched with the first, basic request
    photoModel.photoName = dictionary[@"name"];
    photoModel.identifier = dictionary[@"id"];
    photoModel.photographerName = dictionary[@"user"][@"username"];
    photoModel.rating = dictionary[@"rating"];
    photoModel.thumbnailURL = [self urlForImageSize:2 inArray:dictionary[@"images"]];
    // Extended attributes fetched with subsequent request
    if (dictionary[@"comments_count"]) {
        photoModel.fullsizedURL = [self urlForImageSize:2048
                                        inArray:dictionary[@"images"]];
    }
}

+ (void)downloadThumbnailForPhotoModel:(FRPPhotoModel*)photoModel {
    RAC(photoModel, thumbnailData) = [self download:photoModel.thumbnailURL];
}

+ (void)downloadFullsizedImageForModel:(FRPPhotoModel *)photoModel {
    RAC(photoModel, fullsizedData) = [self download:photoModel.fullsizedURL];
}

+ (RACSignal *)download:(NSString *)urlString {
    NSAssert(urlString, @"URL must not be nil");
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    
    return [[[NSURLConnection rac_sendAsynchronousRequest:request] map:^id _Nullable(RACTuple * _Nullable value) {
        return [value second];
    }] deliverOn:[RACScheduler mainThreadScheduler]];
}

@end
